<?php
namespace Admin\Controller;


use Think\Controller;
use Think\Verify;

class LoginController extends Controller
{
    public function _initialize()
    {
        /* 登录页面没有布局 */
        layout(false);
    }

    public function loginUI()
    {
        $this->display('login');
    }

    public function logout()
    {
        session(null);//清空session
        $this->redirect('/Admin/Login/loginUI');
    }

    public function login()
    {
        if (IS_POST) {
            $user = D('Admin');
//            $chkcode = I('post.chkcode');
//            if($chkcode==NULL || $chkcode == '')
//                $this->retJson(false, '验证码不能为空');
//            if(!$this->chk_chkcode($chkcode)){
//                $this->retJson(false, '验证码不正确');
//            }
            if (!$user->validate($user->_login_validate)->create($_POST)) {
                $this->retJson(false, $user->getError());
            }
            $username = I('post.username');
            $password = I('post.password');
            $data = $user->getUsernameAndPassword($username, $password);
            if (isset($data)) {
                if(!$data['is_use']){
                    $this->retJson(false, '该用户未启用');
                }
                session('admin', $data);
                $data['check'] = true;
                $data['url'] = __CONTROLLER__ . "/../Index/index";
                $this->ajaxReturn($data);
            } else {
                $this->retJson(false, '用户名或密码错误');
            }
        }
    }
    /**校验验证码
     * @param $code 验证码
     * @return bool 是否正确
     */
    public function chk_chkcode($code)
    {
        $verify = new Verify();
        return $verify->check($code);
    }

    // 生成验证码的图片
    public function check_code()
    {
        $config =    array(
            'fontSize'    =>    20,    // 验证码字体大小
            'length'      =>    4,     // 验证码位数
            'useNoise'    =>    true, // 关闭验证码杂点
            'useImgBg' => true,
        );
        $Verify = new Verify($config);
        $Verify->entry();
    }

    /**
     *  向客户端返回json数据
     * @param $check 操作是否成功
     * @param $message 提示信息
     */
    private function retJson($check, $message)
    {
        $json['check'] = $check;
        $json['message'] = $message;
        $this->ajaxReturn($json);
    }
}

